<?php

namespace app\common\service;

use app\index\model\ImportexportModel;
use app\index\service\ImportexportService;

/**
 * excel操作
 * @author xjy
 */
class ExcelLibraryService
{
    //读取数据
    public static function read($param)
    {
        $data = [];
        $error=[];
        $file=$param['_FILES']['file'];
        $ext=pathinfo($file['name'])['extension'];
        if(!in_array($ext,['csv'])){
            $error[]=['msg'=>'文件只支持csv,请下载最新模板上传'];
        }
        if(!empty($error)){
            DownService::error($error,$param['importId']);
            return [];
        }
        try{
            $handle = fopen($file['tmp_name'], 'rb');
        }catch(\Exception $e){
            $error[]=['msg'=>'文件上传失败,请重新上传'];
            DownService::error($error,$param['importId']);
            return [];
        }
        try{
            if ($handle!== FALSE) {
                $line = 0;
                while (($itm = fgetcsv($handle)) != FALSE) {
                    foreach ($itm as $k => &$v) {
                        $v = iconv("GBK", "UTF-8//IGNORE", $v);
                        //$encode = mb_detect_encoding($v, "UTF-8,GB2312,GBK,ASCII,EUC-CN");
                        //$v = mb_convert_encoding($v, "UTF-8", $encode); // 将对应的字符串编码格式全部装换为中文，防止中文乱码
                    }

                    ++$line;
                    if($line==1){
                        //校验行头
                        if(!empty($param['url'])){
                            $checkTitle=self::checkTitle($itm,$param['url']);
                            if ($checkTitle['code'] == 0) {
                                $error=array_merge($error,$checkTitle['data']);
                            }
                        }
                        if(!empty($error)){
                            DownService::error($error,$param['importId']);
                            return [];
                        }
                    }else{
                        if(!empty($itm)&&!empty($itm[0])){
                            $data[]=array_map('trim',$itm);
                        }
                    }
                }
                fclose($handle);
            }
        }catch (\Exception $e){
            $error[]=['msg'=>'上传文件有问题,请下载最新模板上传,如还有问题请联系谢俊宇!'];
            DownService::error($error,$param['importId']);
            return [];
        }

        if(empty($data)){
            $error[]=['msg'=>'上传数据为空'];
            DownService::error($error,$param['importId']);
            return [];
        }
        $res=call_user_func($param['actionAsync'], $data,$param);
        unset($data);
        if(isset($res['code'])){
            if($res['code']=='1'){
                //成功
                //DownService::export($res['data']['list'], $res['data']['title'], $param['importId']);
                ImportexportModel::dbUpdateImportexport($param['importId'], ['state'=>3,'result'=>1,'complete_time'=>date('Y-m-d H:i:s')]);

            }else{
                //导出错误信息
                if(!empty($res['data'])&&empty($res['data'][0]['msg'])){
                    $msg=[];
                    foreach ($res['data'] as $v3){
                        $msg[]=['msg'=>$v3];
                    }
                    DownService::error($msg,$param['importId'],'',$res['code']);
                }else{
                    DownService::error($res['data'],$param['importId'],'',$res['code']);
                }
            }
        }else{
            //全部失败
            ImportexportModel::dbUpdateImportexport($param['importId'], ['state'=>3,'result'=>2]);
        }
    }
    //检验表头
    public static function checkTitle($data,$url){
        //获取模板文件表头
        $title=[];
        $utf8=false;
        if (($handle = fopen(ROOT_PATH . 'public'.$url, 'rb')) !== FALSE) {
            while (($itm = fgetcsv($handle)) != FALSE) {
                foreach ($itm as $k => &$v) {
                    $v = iconv("GBK", "UTF-8//IGNORE", $v);
                }
                break;
            }
            $title=$itm;
            fclose($handle);
        }
        if(empty($title)){
            return ['code'=>1];
        }
        $msg=[];
        if(count($title)!=count($data)){
            $msg[]=['msg'=>"表头不一致,请下载最新模板上传"];
        }
        foreach ($title as $k2=>$v2){
            if(empty($data[$k2])){
                $msg[]=['msg'=>"表头不一致,请下载最新模板上传"];
            }elseif ($v2!=$data[$k2]){
                $msg[]=['msg'=>"上传表头{$data[$k2]}和模板表头{$v2}不一致,请下载最新模板上传"];
            }
        }
        if($msg){
            return ['code'=>0,'data'=>$msg];
        }else{
            return ['code'=>1];
        }
    }
    //移动文件
    public static function moveFile($param){
        $name=iconv("UTF-8", "GBK//IGNORE", $param['_FILES']['file']['name']);
        $date=date('YmdHis');
        $name=$date.$name;
        move_uploaded_file($param['_FILES']['file']['tmp_name'],FILE_PATH.'upload/'.$name);
        $name=$date.$param['_FILES']['file']['name'];
        $param['_FILES']['file']['tmp_name']=FILE_PATH.'upload/'.$name;
        ImportexportModel::dbUpdateImportexport($param['importId'],['source_file_name'=>$param['_FILES']['file']['name'],'source_file_url'=>'/attachment/upload/'.$name]);
    }

}
